package org.emergency.framework.model.contactTree;

import java.io.Serializable;
import java.util.List;

import org.apache.log4j.Logger;
import org.emergency.framework.dao.oa.ITbPermissionDAO;
import org.emergency.framework.model.TbPermission;


/**
 * 权限树,保存在服务器内存 单例模式——线程安全
 * 
 * @author 张颢铧
 * 
 */

public class TbPermissionTree extends TbPermissionAbstractTree implements Serializable {
	private static Logger logger = Logger.getLogger(TbPermissionTree.class);
	/**
	 * 
	 */
	private static final long serialVersionUID = -3149071186653147609L;
	private volatile static TbPermissionTree instance = null;
	private static Object lock = new Object();
	private TbPermissionTree() {

	}

	/**
	 * 用来得到tree的
	 * @param roleDAO
	 * @return
	 */
	public static TbPermissionTree getInstance(ITbPermissionDAO dao) {
		if (instance == null) {
			synchronized (lock) {
				if (instance == null) {
					instance = new TbPermissionTree();
					logger.info("TbRoleTree----------reloading");
					instance.reloadEmergencyDept(dao);
				}
			}
		}
		return instance;
	}
	
	/**
	 * 用来重新load的
	 * @param roleDAO
	 */
	public static void updateTbPermissionTree(ITbPermissionDAO dao) {
			synchronized (lock) {
				if (instance == null) {
					instance = new TbPermissionTree();
					logger.info("TbRoleTree----------reloading");
					instance.reloadEmergencyDept(dao);
				}
			}
	}
	
	/**
	 * 直接reload
	 * @param dao
	 */
	public static void reloadTree(ITbPermissionDAO dao){
		instance.reloadEmergencyDept(dao);
	}

	@Override
	protected TbPermissionTreeNode transform(Object info) {
		// 将Object对象转换为树的结点
		TbPermission permission = (TbPermission) info;
		TbPermissionTreeNode node = new TbPermissionTreeNode();
		node.setNodeId(permission.getPId());
		node.setName(permission.getPName());
		node.setDesc(permission.getDescription());
		
		if (permission.getParentPermission() != null) {	//父节点,把node的parentid放进去
			node.setParentId(permission.getParentPermission().getPId());
		}
		node.setBindData(permission);// 绑定
		return node;
	}

	/**
	 * 找到nodes，放到reload去
	 * @param deptDao
	 */
	public void reloadEmergencyDept(ITbPermissionDAO dao) {
		List objects;
		try {
			objects = dao.findAll();//得到 list<dept>
			super.reload(objects);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
